// 用户登录状态管理

import { createContext, JSX, memo, useEffect, useState } from "react";
import { useAppDispatch, useAppSelector } from "../redux";
import { matchRoutes, useLocation, useNavigate } from "react-router";
import { setIsLogin } from "../redux/privates/userInfoSlice";
import { routes } from "../router";
import { getShoppingsApi } from "../request/shoppingCar/getShoppinsApi";

import React from "react"

interface RouteGrandProps {
    children:JSX.Element
}

export const RouteGrandContext = createContext({} as any)

const RouteGrand:React.FC<RouteGrandProps>=memo(({children})=>{
    const dispatch = useAppDispatch()
    const [data,setData] = useState(null)
    const {pathname} = useLocation()    //当前路径
    const navigete = useNavigate()      //用于跳转路由
    const {isLogin} = useAppSelector((state)=>state.userInfo)   //查看是否登录

    // 每个页面一刷新,都重新验证token是否过期
    useEffect(()=>{
        const test = async()=>{
            const res:any = await getShoppingsApi()
            setData(res)
            if(res==401){
                dispatch(setIsLogin(false))
                localStorage.removeItem("userToken")
            }else{
                dispatch(setIsLogin(true))
            }
        }
        const Token = localStorage.getItem("userToken")
        if(Token != null){
            test()
        }
    },[pathname])
    



    // 路由守卫
    useEffect(()=>{
        const Token = localStorage.getItem("userToken")
        const matchMes = matchRoutes(routes,pathname)   //获取匹配当前路由的信息
        const route = matchMes?.[0].route   //获取路由配置信息（路由表里的信息）
        const meta = route?.meta
        // 需要验证登录
        if(meta?.check){
            if(isLogin || Token != null){
                navigete(pathname)
            }else{
                navigete("/login")
            }
        }
    },[pathname])

    return (
        <RouteGrandContext.Provider value={null}>
            {children}
        </RouteGrandContext.Provider>
    )
})



export default RouteGrand